package services

import (
	"github.com/spf13/cast"
	"longmen/server/pkg/common/api_models"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_main"
	"longmen/server/pkg/db/redis/cache"
)

func (s *Service) UnreadMsg(user *models_main.User, req *api_models.UnReadMsgReq) (resp *api_models.UnReadMsgResp, err error) {
	if user.Id <= 0 {
		user.Id = int(util.HashUid(req.DeviceId))
	}

	var session []*models_main.PrivateChatSession
	session, err = db_main.GetPrivateChatSessionList(map[string]interface{}{
		"user_id": user.Id,
	}, "id desc", 0, 0, "")
	if err != nil {
		return
	}

	resp = &api_models.UnReadMsgResp{}
	anchorUserMp := map[string]int{}
	for _, v := range session {
		anchorUserMp[cast.ToString(v.AnchorId)+cast.ToString(v.UserId)] = 1
	}
	for _, v := range session {
		_, ok := anchorUserMp[cast.ToString(v.AnchorId)+cast.ToString(v.UserId)]
		if !ok {
			continue
		}
		num := cache.GetPrivateChatUnread(v.UserId, v.AnchorId)
		resp.UnreadTotal += num
		resp.UnreadAnchorList = append(resp.UnreadAnchorList, api_models.UnreadAnchor{
			AnchorId:  v.AnchorId,
			UserId:    v.UserId,
			UnreadNum: num,
		})
		delete(anchorUserMp, cast.ToString(v.AnchorId)+cast.ToString(v.UserId))
	}
	return
}

//ReadRecord 不处理，getRecordDetail 已ReSetPrivateChatUnreadNum
func (s *Service) ReadRecord(user *models_main.User, req *api_models.ReadRecordReq) (err error) {
	if user.Id <= 0 {
		user.Id = util.HashUid(req.DeviceId)
	}

	cache.ReSetPrivateChatUnreadNum(req.AnchorId, user.Id)
	return
}
